package com.example.shutdown_v1.controller;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Set;

/**
 * Redis调试控制器
 * 用于查看Redis中的电力设备数据
 */
@RestController
@RequestMapping("/api/debug/redis")
@Slf4j
@RequiredArgsConstructor
@CrossOrigin(originPatterns = "*")
public class RedisDebugController {
    
    private final RedisTemplate<String, Object> redisTemplate;
    
    /**
     * 查看所有电力相关的Redis key
     */
    @GetMapping("/power-keys")
    public ResponseEntity<Map<String, Object>> getPowerKeys() {
        try {
            Set<String> queryKeys = redisTemplate.keys("power_query:*");
            Set<String> responseKeys = redisTemplate.keys("power_response:*");
            Set<String> statusKeys = redisTemplate.keys("merchant_power_status:*");
            
            return ResponseEntity.ok(Map.of(
                "success", true,
                "queryKeys", queryKeys != null ? queryKeys : Set.of(),
                "responseKeys", responseKeys != null ? responseKeys : Set.of(),
                "statusKeys", statusKeys != null ? statusKeys : Set.of(),
                "totalKeys", (queryKeys != null ? queryKeys.size() : 0) + 
                           (responseKeys != null ? responseKeys.size() : 0) + 
                           (statusKeys != null ? statusKeys.size() : 0)
            ));
        } catch (Exception e) {
            log.error("获取Redis keys失败", e);
            return ResponseEntity.internalServerError().body(Map.of(
                "success", false,
                "message", "获取失败: " + e.getMessage()
            ));
        }
    }
    
    /**
     * 查看指定商家的电力状态数据
     */
    @GetMapping("/merchant/{merchantId}")
    public ResponseEntity<Map<String, Object>> getMerchantData(@PathVariable String merchantId) {
        try {
            String statusKey = "merchant_power_status:" + merchantId;
            Map<Object, Object> statusData = redisTemplate.opsForHash().entries(statusKey);
            
            // 查看查询记录
            Set<String> queryKeys = redisTemplate.keys("power_query:" + merchantId + ":*");
            Set<String> responseKeys = redisTemplate.keys("power_response:" + merchantId + ":*");
            
            return ResponseEntity.ok(Map.of(
                "success", true,
                "merchantId", merchantId,
                "statusKey", statusKey,
                "statusData", statusData,
                "hasStatusData", !statusData.isEmpty(),
                "queryKeys", queryKeys != null ? queryKeys : Set.of(),
                "responseKeys", responseKeys != null ? responseKeys : Set.of()
            ));
        } catch (Exception e) {
            log.error("获取商家数据失败 - 商家:{}", merchantId, e);
            return ResponseEntity.internalServerError().body(Map.of(
                "success", false,
                "message", "获取失败: " + e.getMessage()
            ));
        }
    }
    
    /**
     * 查看指定key的详细数据
     */
    @GetMapping("/key/{keyName}")
    public ResponseEntity<Map<String, Object>> getKeyData(@PathVariable String keyName) {
        try {
            Object data = redisTemplate.opsForValue().get(keyName);
            Map<Object, Object> hashData = redisTemplate.opsForHash().entries(keyName);
            Long ttl = redisTemplate.getExpire(keyName);
            
            return ResponseEntity.ok(Map.of(
                "success", true,
                "keyName", keyName,
                "exists", redisTemplate.hasKey(keyName),
                "valueData", data,
                "hashData", hashData,
                "ttl", ttl != null ? ttl : -1,
                "type", redisTemplate.type(keyName).name()
            ));
        } catch (Exception e) {
            log.error("获取key数据失败 - key:{}", keyName, e);
            return ResponseEntity.internalServerError().body(Map.of(
                "success", false,
                "message", "获取失败: " + e.getMessage()
            ));
        }
    }
    
    /**
     * 清除指定商家的所有电力数据
     */
    @DeleteMapping("/merchant/{merchantId}")
    public ResponseEntity<Map<String, Object>> clearMerchantData(@PathVariable String merchantId) {
        try {
            Set<String> allKeys = redisTemplate.keys("*" + merchantId + "*");
            if (allKeys != null && !allKeys.isEmpty()) {
                redisTemplate.delete(allKeys);
            }
            
            return ResponseEntity.ok(Map.of(
                "success", true,
                "message", "已清除商家 " + merchantId + " 的所有数据",
                "clearedKeys", allKeys != null ? allKeys : Set.of()
            ));
        } catch (Exception e) {
            log.error("清除商家数据失败 - 商家:{}", merchantId, e);
            return ResponseEntity.internalServerError().body(Map.of(
                "success", false,
                "message", "清除失败: " + e.getMessage()
            ));
        }
    }
}
